package org.truenewx.tnxjee.repo.jpa.converter;

import jakarta.persistence.AttributeConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.truenewx.tnxjee.core.context.SpringContextHolder;
import org.truenewx.tnxjee.core.enums.EnumDictResolver;
import org.truenewx.tnxjee.core.enums.EnumItem;

/**
 * 用@{@link org.truenewx.tnxjee.core.enums.annotation.EnumProperty}标注的实体属性转换器，由子类提供枚举类型名称
 */
public abstract class EnumPropertyConverter implements AttributeConverter<String, String> {

    private String type;
    private String subType;

    public EnumPropertyConverter(String type) {
        this.type = type;
    }

    public EnumPropertyConverter(String type, String subType) {
        this.type = type;
        this.subType = subType;
    }

    private EnumDictResolver getEnumDictResolver() {
        return SpringContextHolder.getBean(EnumDictResolver.class);
    }

    @Override
    public String convertToDatabaseColumn(String attribute) {
        if (StringUtils.isNotBlank(attribute)) {
            return getEnumDictResolver().getValue(this.type, this.subType, attribute);
        }
        return null;
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
        if (StringUtils.isNotBlank(dbData)) {
            EnumItem item = getEnumDictResolver().getEnumItemByValue(this.type, this.subType, dbData,
                    LocaleContextHolder.getLocale());
            if (item != null) {
                return item.getKey();
            }
        }
        return null;
    }

}
